/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { PlusOutlined } from '@ant-design/icons';
import { Button, Col, message, Row } from 'antd';
import type { Address_Type } from '@/components/KbAddressSelect/index.d';
import React, { useState, useMemo } from 'react';
import KbAddressSelect from './KbAddressSelect';
interface AgencyAreaType {
  onChange?: (value: any) => void;
  value?: Address_Type[];
}

const formatAddress = (list: Address_Type[] = []) => {
  const { province, city } = list[0] || {};
  return `${province}${city}(${list.map((item) => item.district).toString()})`;
};

const AgencyArea: React.FC<AgencyAreaType> = (props) => {
  const { value = [] } = props;
  const [seleceValue, setSeleceValue] = useState<(string | number)[]>([]);
  const [selectOptions, setSelectOptions] = useState<Record<string, string>[][]>([]);

  const listArray = useMemo(
    () =>
      Array.from(new Set(value.map((item: { city_code: string }) => item.city_code))).map(
        (item) => {
          return {
            index: item || '',
            value: value.filter((itemm: { city_code: string }) => itemm.city_code == item),
          };
        },
      ),
    [value],
  );

  const onDetele = (index: string) => {
    const newValue = value.filter((item: { city_code: string }) => item.city_code != index);
    if (props?.onChange) {
      props?.onChange([...newValue]);
    }
  };

  const onSelectChange = (values: (string | number)[], options: Record<string, string>[][]) => {
    setSeleceValue(values);
    setSelectOptions(options);
  };

  const onDropdownVisibleChange = (status: boolean) => {
    const onChange = props.onChange ? props.onChange : () => {};
    if (!status && selectOptions.length) {
      const format = selectOptions.map((item) => {
        return {
          province: item[0].label,
          province_code: item[0].code,
          city: item[1].label,
          city_code: item[1].code,
          district: item[2].label,
          district_code: item[2].code,
        };
      });
      const isRepetition = format.some((item) =>
        value.some((itemm: { district_code: string }) => itemm.district_code == item.district_code),
      );
      if (isRepetition) {
        message.info('添加过相同区域地址，已进行合并');
        onChange([
          ...value,
          ...format.filter(
            (item) =>
              !value.some(
                (itemm: { district_code: string }) => itemm.district_code == item.district_code,
              ),
          ),
        ]);
      } else {
        message.info('添加成功');
        onChange([...value, ...format]);
      }
      setSeleceValue([]);
      setSelectOptions([]);
    }
  };

  return (
    <>
      {listArray.map((item) => (
        <Row
          key={item.index}
          justify='space-between'
          align='middle'
          wrap={false}
          style={{ margin: '0 10px' }}
        >
          <Col>{formatAddress(item.value)}</Col>
          <Col span={4} style={{ textAlign: 'right' }}>
            <a onClick={onDetele.bind(null, item.index)}>删除</a>
          </Col>
        </Row>
      ))}
      <KbAddressSelect
        level={2}
        multiple
        value={seleceValue}
        onChange={(values, options) => onSelectChange(values, options)}
        onDropdownVisibleChange={onDropdownVisibleChange}
      >
        <Button type='link' icon={<PlusOutlined />}>
          添加新地址
        </Button>
      </KbAddressSelect>
    </>
  );
};

export default React.memo(AgencyArea, () => false);
